﻿using Newtonsoft.Json;
using Onetube.Providers.Interfaces;
using System;
using Windows.Storage;

namespace Onetube.Providers
{
   public class SettingsProvider:ISettingsProvider
    {
        public async void SetValue<T>(string key, T value)
        {
            try
            {
                StorageFile storageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(key, CreationCollisionOption.ReplaceExisting);
               
                var content = JsonConvert.SerializeObject(value);

                var task= FileIO.WriteTextAsync(storageFile, content);
                task.AsTask().Wait(TimeSpan.FromMilliseconds(500));
                storageFile = null;
            }
            catch (Exception ex)
            {
            }
        }

        public T GetValue<T>(string key)
        {
           try
            {
                StorageFile storageFile = ApplicationData.Current.LocalFolder.CreateFileAsync(key, CreationCollisionOption.OpenIfExists).AsTask().Result;
                var content = FileIO.ReadTextAsync(storageFile).AsTask().Result;
                if (string.IsNullOrEmpty(content))
                    return default(T);
                var obj = JsonConvert.DeserializeObject<T>(content);

                return obj;
            }
            catch (Exception ex)
            {
            }
            return default(T);
        }
    }
}
